/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.tspp.dao;

import com.tspp.common.ResourceManager;
import com.tspp.dao.dto.User;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * Manipulates users(retrievs users types and checks if users exist)
 * @author Maks
 */
public class UserDao {

    private static String SQL_GET_TYPE_OF_USER = "SELECT USERTYPE FROM USERS WHERE LOGIN = ? AND PASSWORD = ?";
    private static int TYPE_COLUMN = 1;

    /**
     * Check if the user with such login and password exist. If true, return its type
     * @param user specified user
     * @return usertype or null if user doesn't exist
     * @throws DaoException
     */
    public UserType getTypeOfUser(User user) throws DaoException {
        Connection con = null;
        PreparedStatement st = null;
        ResultSet rs = null;
        UserType type = null;
        try {
            con = ResourceManager.getConnection();
            st = con.prepareStatement(SQL_GET_TYPE_OF_USER);
            int index = 1;
            st.setString(index++, user.getLogin());
            st.setString(index++, user.getPassword());
            rs = st.executeQuery();
            if (rs.next()) {
                type = UserType.getType(rs.getInt(TYPE_COLUMN));
            }
            return type;
        } catch (Exception ex) {
            throw new DaoException("Exception: " + ex.getMessage());
        } finally {
            ResourceManager.close(rs);
            ResourceManager.close(st);
            ResourceManager.close(con);
        }
    }
}
